from django.core.paginator import Paginator, InvalidPage, EmptyPage

def get_pageitems(request, objects, page_var='page', perpage_var='perpage', default_perpage=30):
    try:
        page = int(request.GET.get(page_var))
    except (TypeError, ValueError):
        page = None

    if not page or page < 1:
        page = 1

    try:
        perpage = int(request.GET.get(perpage_var))
    except (TypeError, ValueError):
        perpage = default_perpage

    paginator = Paginator(objects, perpage)
    try:
        pageitems = paginator.page(page)
    except (EmptyPage, InvalidPage):
        pageitems = paginator.page(paginator.num_pages)

    return pageitems

